#!/usr/bin/env python3
"""
Translation update script for PDF Splitter.
Extracts translatable strings and updates .ts files.
"""

import os
import subprocess
import sys
from pathlib import Path

# Get project root
PROJECT_ROOT = Path(__file__).parent.parent
SRC_DIR = PROJECT_ROOT / "src"
I18N_DIR = SRC_DIR / "pdf_splitter" / "i18n"
RESOURCES_DIR = I18N_DIR / "resources"

# Supported languages
LANGUAGES = ["en_US", "zh_CN"]

def run_command(cmd: list, cwd: Path = None) -> bool:
    """Run a shell command and return True if successful."""
    try:
        result = subprocess.run(
            cmd,
            cwd=cwd or PROJECT_ROOT,
            check=True,
            capture_output=True,
            text=True
        )
        if result.stdout:
            print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error running command: {' '.join(cmd)}")
        print(f"Error: {e}")
        if e.stdout:
            print(f"Stdout: {e.stdout}")
        if e.stderr:
            print(f"Stderr: {e.stderr}")
        return False

def extract_translations():
    """Extract translatable strings from source code."""
    print("Extracting translations...")

    # Create .pro file for pylupdate
    pro_file = PROJECT_ROOT / "translations.pro"
    with open(pro_file, 'w', encoding='utf-8') as f:
        f.write("SOURCES = \\\n")

        # Find all Python files
        for py_file in SRC_DIR.rglob("*.py"):
            f.write(f"    {py_file.relative_to(PROJECT_ROOT)} \\\n")

        f.write("\nTRANSLATIONS = \\\n")
        for lang in LANGUAGES:
            ts_file = RESOURCES_DIR / f"{lang}.ts"
            f.write(f"    {ts_file.relative_to(PROJECT_ROOT)} \\\n")

        f.write("\nCODECFORTR = UTF-8\n")
        f.write("CODECFORSRC = UTF-8\n")

    # Run pylupdate6
    cmd = ["pylupdate6", "translations.pro"]
    if run_command(cmd):
        print("Successfully extracted translations!")
        # Clean up .pro file
        pro_file.unlink()
        return True
    else:
        print("Failed to extract translations!")
        pro_file.unlink(missing_ok=True)
        return False

def compile_translations():
    """Compile .ts files to .qm files."""
    print("Compiling translations...")

    for lang in LANGUAGES:
        ts_file = RESOURCES_DIR / f"{lang}.ts"
        qm_file = RESOURCES_DIR / f"{lang}.qm"

        if ts_file.exists():
            cmd = ["pylrelease6", str(ts_file.relative_to(PROJECT_ROOT))]
            if run_command(cmd):
                print(f"Compiled {lang}.ts -> {lang}.qm")
            else:
                print(f"Failed to compile {lang}.ts")
                return False
        else:
            print(f"Warning: {ts_file} does not exist")

    return True

def main():
    """Main function."""
    print("PDF Splitter Translation Update Tool")
    print("=" * 50)

    # Ensure resources directory exists
    RESOURCES_DIR.mkdir(parents=True, exist_ok=True)

    # Command line arguments
    if len(sys.argv) > 1:
        if sys.argv[1] == "extract":
            success = extract_translations()
        elif sys.argv[1] == "compile":
            success = compile_translations()
        elif sys.argv[1] == "all":
            success = extract_translations() and compile_translations()
        else:
            print(f"Unknown command: {sys.argv[1]}")
            print("Usage: python update_translations.py [extract|compile|all]")
            success = False
    else:
        # Default: extract and compile
        success = extract_translations() and compile_translations()

    if success:
        print("\nTranslation update completed successfully!")
        sys.exit(0)
    else:
        print("\nTranslation update failed!")
        sys.exit(1)

if __name__ == "__main__":
    main()